import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';

import '../config.dart';
import '../public.dart';
import 'package:dio/dio.dart';

class LoadConfig {
  static Future preLoad() async {
    //缓存初始化
    initHttp();
    print("开始请求权限");
    await PermissionManager.requestPermission(Permission.storage);
    await StorageManager.init();
    //初始化router
    final router = new Router();
    Routes.configureRoutes(router);
    AppConfig.router = router;
    FlutterBugly.init(androidAppId: "752612af6b");
  }

  static void initHttp() {
    BaseOptions options = HttpManager.getDefOptions();
    HttpConfig config = new HttpConfig(
      options: options,
      interceptorsWrapper: InterceptorsWrapper(
        onRequest: (RequestOptions options) {
          print("发送请求");
          return options;
        },
        onResponse: (Response response) {
          print("得到返回");
          return response; // continue
        },
        onError: (DioError e) {
          print("返回错误代码了");
          formatError(e);
          return DioError(error: e);
        },
      ),
    );
    HttpManager().setConfig(config);
  }

  /*
   * error统一处理
   */
  static void formatError(DioError e) {
    print(e);
    if (e.type == DioErrorType.CONNECT_TIMEOUT) {
      // It occurs when url is opened timeout.
      print("连接超时");
      Fluttertoast.showToast(msg: "{msg:连接超时,error_code:-1}");
    } else if (e.type == DioErrorType.SEND_TIMEOUT) {
      // It occurs when url is sent timeout.
      print("请求超时");
      Fluttertoast.showToast(msg: "{msg:请求超时,error_code:-1}");
    } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
      //It occurs when receiving timeout
      print("响应超时");
      Fluttertoast.showToast(msg: "{msg:响应超时,error_code:-1}");
    } else if (e.type == DioErrorType.RESPONSE) {
      // When the server response, but with a incorrect status, such as 404, 503...
      print("出现异常");
      Fluttertoast.showToast(msg: "{msg:服务器现异常,error_code:503}");
    } else if (e.type == DioErrorType.CANCEL) {
      // When the request is cancelled, dio will throw a error with this type.
      print("请求取消");
//      Fluttertoast.showToast(msg: "{msg:连接超时,error_code:-1}");
    } else {
      //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
      print("未知错误");
      Fluttertoast.showToast(msg: "{msg:请求出错,error_code:-1}");
    }
  }
}
